/**
 * 响应模式接口
 * cgi 模式: 发送cgi程序生成的标准输出
 * 静态模式: 读取静态文件并发送
 */
#include "include/core.h"



int cgi_link(char * url, char * buffer, int remoteSocket)
{
    int filehd, pubswap, reqsize;
    int swap, api[2], ipa[2];  // 两个管道
    char reqheader[170];
    pid_t pid;
    if (pipe(api) < 0 || pipe(ipa) < 0) {
        puts("创建管道失败\n");
        exit(0);
    }
    if ((pid = fork()) < 0) {
        puts("创建进程失败\n");
        exit(0);
    } else if (pid > 0) {
        close(api[0]);
        close(ipa[1]);
        sprintf(reqheader, "%s text/html; charset=utf-8\r\n", HEAD_200);
        strcpy(buffer, reqheader);
        send(remoteSocket, buffer, reqsize + (int) sizeof(reqheader), 0);
        memset(buffer, 0, sizeof(buffer));
        if ((swap = read(ipa[0], buffer, REMOTE_BUF_SIZE)) < 0) {
            puts("检测到条件不符\n");
            exit(1);
        }
        send(remoteSocket, buffer, swap, 0);
        shutdown(remoteSocket, 2);
        close(filehd);
    } else {
        close(api[1]);
        close(ipa[0]);
        if (api[0] != STDIN_FILENO) {
            mcc(dup2(api[0], STDIN_FILENO), STDIN_FILENO);
            close(api[0]);
        }
        if (api[0] != STDOUT_FILENO) {
            mcc(dup2(ipa[1], STDOUT_FILENO), STDOUT_FILENO);
            close(ipa[1]);
        }
        execl(url, "apue", (char *)0);
    }
    return 0;
}

int static_link(char * url, char * buffer, int remoteSocket)
{
    int filehd, pubswap, reqsize;
    char mimetype[40];  // 文件的 mime 类型
    char reqheader[170];

    if ((filehd = open(url, O_RDONLY)) < 0) {  // 取文件类型
        // 无法打开页面，404 not found
        filehd = open(REQ_FILE_404, O_RDONLY);
        sprintf(reqheader, "%s\r\n", HEAD_HTML_404);
    } else {
        file_mime(url, mimetype);
        sprintf(reqheader, "%s%s\r\n", HEAD_200, mimetype);
    }
    strcpy(buffer, reqheader);
    send(remoteSocket, buffer, reqsize + (int) sizeof(reqheader), 0);
    // 读取并得到真实大小
    if ((pubswap = read(filehd, buffer, REMOTE_BUF_SIZE)) < 0) {
        puts("读取文件失败");
        shutdown(remoteSocket, 2);
        exit(0);
    }
    send(remoteSocket, buffer, pubswap, 0);
    shutdown(remoteSocket, 2);
    close(filehd);
    return 0;
}

int mcc(int a, int b) {
    if (a != b) {
        puts("检测到条件不符\n");
        exit(1);
    }
}